<template>
  <div class="header">
    <div class="header-left">
      <el-button 
        text 
        @click="toggleSidebar"
        class="collapse-btn"
      >
        <el-icon size="20">
          <Expand v-if="isCollapse" />
          <Fold v-else />
        </el-icon>
      </el-button>
      
      <!-- 面包屑导航 -->
      <el-breadcrumb class="breadcrumb">
        <el-breadcrumb-item 
          v-for="item in breadcrumbs" 
          :key="item.path"
        >
          {{ item.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <div class="header-right">
      <!-- 搜索 -->
      <el-input
        v-model="searchValue"
        placeholder="搜索"
        class="search-input"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <!-- 通知 -->
      <el-badge :value="12" class="notification-badge">
        <el-button text>
          <el-icon size="20"><Bell /></el-icon>
        </el-button>
      </el-badge>
      
      <!-- 用户信息 -->
      <el-dropdown>
        <span class="user-info">
          <el-avatar size="small" :src="userAvatar">
            <el-icon><User /></el-icon>
          </el-avatar>
          <span class="username">{{ currentUser?.Username || '未登录' }}</span>
          <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goToProfile">
              <el-icon><User /></el-icon>
              个人中心
            </el-dropdown-item>
            <el-dropdown-item >
              <el-icon><Setting /></el-icon>
              设置
            </el-dropdown-item>
            <el-dropdown-item divided @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted,onUnmounted } from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 从父组件接收的props
const props = defineProps({
  isCollapse: Boolean,
  toggleSidebar: Function,
  userAvatar: String
})

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
// const searchValue = ref('')

// 获取当前登录用户信息
// const currentUser = ref(JSON.parse(localStorage.getItem('user')))
const currentUser = computed(() => authStore.user)


// 跳转到个人中心
const goToProfile = () => {
  router.push('/users/profile')
}

// 跳转到设置页面
// const goToSettings = () => {
//   router.push('/system/settings')
// }

// // 监听登录事件
// const updateUser = (event) => {
//   currentUser.value = event.detail || JSON.parse(localStorage.getItem('user'))
// }

// onMounted(() => {
//   window.addEventListener('user-login', updateUser)
// })

// onUnmounted(() => {
//   window.removeEventListener('user-login', updateUser)
// })

// 退出登录
const handleLogout = async () => {
  try {
      localStorage.removeItem('user')
  currentUser.value = null
  window.dispatchEvent(new Event('user-logout'))
  router.push('/')
    
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}

// 响应式数据
const searchValue = ref('')

// 路由名称映射
const routeNames = {
  '/dashboard': '工作台',
  '/users/list': '用户列表',
  '/users/profile': '个人设置',
  '/permissions/roles': '角色管理',
  '/permissions/menus': '菜单管理',
  '/permissions/items': '权限项管理',
  '/content/articles': '文章管理',
  '/content/files': '文件管理',
  '/system/settings': '系统设置',
  '/system/logs': '日志管理'
}
const parentRoutes = {
  '/users': '用户管理',
  '/permissions': '权限管理',
  '/content': '内容管理',
  '/system': '系统管理'
}

// 计算属性
const breadcrumbs = computed(() => {
  const pathSegments = route.path.split('/').filter(Boolean)
  const breadcrumbs = []
  
  let currentPath = ''
  let childName = ""
  for (const segment of pathSegments) {
    currentPath += `/${segment}`
    childName = routeNames[currentPath]
    if (childName) {
      breadcrumbs.push({ name:childName, path: currentPath })   
    }
  }      

  if (childName!=='工作台') {
    const parentPath = breadcrumbs[breadcrumbs.length - 1].path   
    const parentName = parentRoutes['/'+parentPath.split('/')[1]]     
    if (parentName) {
      breadcrumbs[breadcrumbs.length - 1] = { name: parentName +' / '+ childName, path: currentPath }
    }
  }
  return breadcrumbs
})
</script>

<style scoped>
.header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  flex-shrink: 0;
  width: 100%;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
  margin-right: 20px;
}

.collapse-btn {
  margin-right: 20px;
  padding: 0;
  width: 40px;
  height: 40px;
  flex-shrink: 0;
}

.breadcrumb {
  margin-left: 12px;
  flex: 1;
  min-width: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-shrink: 0;
}

.search-input {
  width: 200px;
  flex-shrink: 0;
}

.notification-badge {
  cursor: pointer;
  flex-shrink: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
  white-space: nowrap;
  flex-shrink: 0;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.username {
  font-size: 14px;
  color: #303133;
}

.dropdown-icon {
  font-size: 12px;
  color: #909399;
}
</style>